package edu.xlh.travel.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeRefundRequest;
import edu.xlh.travel.aipay.util.AlipayConfig;
import edu.xlh.travel.aipay.util.KeyUtil;
import edu.xlh.travel.dao.ScenicDao;
import edu.xlh.travel.enumeration.OrderStatusEnum;
import edu.xlh.travel.enumeration.OrderTypeEnum;
import edu.xlh.travel.enumeration.ScoreSourceEnum;
import edu.xlh.travel.pojo.*;
import edu.xlh.travel.service.*;
import edu.xlh.travel.util.DateTimeUtil;
import edu.xlh.travel.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Transactional
@Service
public class CallBackServiceImpl implements CallBackService {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private FlowService flowService;
    @Autowired
    private ForeHotelOrderService foreHotelOrderService;
    @Autowired
    private ScoreDetailService scoretDetailService;

    @Override
    public String alipayReturnNotice(HttpServletRequest request, ModelMap model) throws UnsupportedEncodingException, AlipayApiException {
        System.out.println("支付成功, 进入同步通知接口...");
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            String orderTypePrefix = String.valueOf(out_trade_no.charAt(0));
            String orderId = out_trade_no.substring(1);

            //获取当前时间
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
            Flow flow = new Flow();

            //积分的userId
            String userId;
            Integer qty;
            if (OrderTypeEnum.scenicOrder.getCode().equals(orderTypePrefix)) {
                //修改叮当状态，改为 支付成功，已付款;
                Orders order=new Orders();
                order.setId(orderId);
                order.setPayment(BigDecimal.valueOf(Double.valueOf(total_amount)));
                order.setPaytime(DateTimeUtil.strToDate(date,"yyyy-MM-dd HH:mm:ss"));
                order.setModifyTime(DateTimeUtil.strToDate(date,"yyyy-MM-dd HH:mm:ss"));
                order.setStatus(String.valueOf(OrderStatusEnum.delivery.getCode()));
                ordersService.updateOrderByEntitiy(order);
                Orders order2=ordersService.findById(orderId);
                userId = order2.getUserId();
                qty = order2.getQty();
                flow.setBuyCounts(qty);
                flow.setProductId(order2.getScenicId());
            } else {
                Hotel_orders hotel_orders2 = foreHotelOrderService.findById(orderId);
                Hotel_orders hotel_orders =new Hotel_orders();
                hotel_orders.setId(orderId);
                hotel_orders.setPayment(BigDecimal.valueOf(Double.valueOf(total_amount)));
                hotel_orders.setPaytime(DateTimeUtil.strToDate(date,"yyyy-MM-dd HH:mm:ss"));
                hotel_orders.setModifyTime(DateTimeUtil.strToDate(date,"yyyy-MM-dd HH:mm:ss"));
                if (OrderStatusEnum.reletNoPay.getCode().equals(hotel_orders2.getStatus())) {
                    //保持子订单与母订单状态一致性
                    Hotel_orders parentHotelOrder = foreHotelOrderService.findById(hotel_orders2.getHeadOrderId());
                    hotel_orders.setStatus(String.valueOf(parentHotelOrder.getStatus()));
                } else  {
                    hotel_orders.setStatus(String.valueOf(OrderStatusEnum.delivery.getCode()));
                }
                foreHotelOrderService.updateHotelOrderByEntitiy(hotel_orders);
                userId = hotel_orders2.getUserId();
                qty = hotel_orders2.getQty();
                flow.setBuyCounts(qty);
                flow.setProductId(hotel_orders2.getScenicId());
            }

            //同时新增支付流水
            String flowid= KeyUtil.genUniqueKey();
            flow.setId(flowid);
            flow.setFlowNum(trade_no);
            flow.setCreateTime(new Date());
            flow.setOrderNum(orderId);
            flow.setPaidAmount(total_amount);
            flow.setPaidMethod(1);
            //TODO 判断是景点门票还是酒店门票
            /*flow.setProductId(order2.getScenicId());*/
            flowService.insert(flow);
            //Product product = productService.selectByPrimaryKey(order2.getProductId());

            //积分操作
            scoretDetailService.scoreOperation(userId , qty);


            System.out.println("********************** 支付成功(支付宝同步通知) **********************");
            System.out.println("* 订单号: {}"+ out_trade_no);
            System.out.println("* 支付宝交易号: {}"+ trade_no);
            System.out.println("* 实付金额: {}"+total_amount);
            //模拟代码
           /* Orders orders1 = ordersDao.findById(out_trade_no).get();
            Scenic scenic = scenicDao.findById(orders1.getScenicId()).get();
            System.out.println("* 购买产品: {}"+scenic.getName());
            System.out.println("***************************************************************");

            model.put("out_trade_no",out_trade_no);//订单编号
            model.put("trade_no",trade_no);//支付宝交易号
            model.put("total_amount",total_amount);//实付金额
            model.put("productName",scenic.getName());//购买产品*/
        }else {
            System.out.println("支付, 验签失败...");
        }
        return "user/payResultReturnNoticePage";
    }

    @Override
    public String alipayNotifyNotice(HttpServletRequest request) throws Exception{
        System.out.println("支付成功, 进入异步通知接口...");

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

		/* 实际验证过程建议商户务必添加以下校验：
		1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
		2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
		3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
		4、验证app_id是否为该商户本身。
		*/
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                // 修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
                //修改叮当状态，改为 支付成功，已付款;
              /*  Orders orders=new Orders();
                orders.setId(out_trade_no);
                orders.setOrderStatus(String.valueOf(OrderStatusEnum.PAID));
                orders.setPaidAmount(total_amount);
                orders.setPaidTime(new Date());
                ordersService.updateorder(orders);*/


                //同时新增支付流水
               /* Orders order2=ordersService.selectByPrimaryKey(out_trade_no);
                Flow flow = new Flow();
                String flowid=KeyUtil.genUniqueKey();
                flow.setId(flowid);
                flow.setFlowNum(trade_no);
                flow.setBuyCounts(order2.getBuyCounts());
                flow.setCreateTime(new Date());
                flow.setOrderNum(out_trade_no);
                flow.setPaidAmount(total_amount);
                flow.setPaidMethod(1);
                flow.setProductId(order2.getProductId());
                flowService.insert(flow);
                Product product = productService.selectByPrimaryKey(order2.getProductId());*/

                System.out.println("********************** 支付成功(支付宝异步通知) **********************");
                System.out.println("* 订单号: {}"+ out_trade_no);
                System.out.println("* 支付宝交易号: {}"+trade_no);
                System.out.println("* 实付金额: {}"+total_amount);
                /*System.out.println("* 购买产品: {}"+product.getName());*/
                System.out.println("***************************************************************");
            }
            System.out.println("支付成功...");

        }else {//验证失败
            System.out.println("支付, 验签失败...");
        }

        return "success";
    }

    @Override
    public String refund(String orderid) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no = orderid;

        Flow flow=flowService.findById(orderid);
        //支付宝交易号
        String trade_no = flow.getFlowNum();

        //请二选一设置
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = flow.getPaidAmount();
        //退款的原因说明
        String refund_reason = "退款原因";

        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
        String out_request_no = flow.getId();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"trade_no\":\""+ trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"refund_reason\":\""+ refund_reason +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");

        //请求
        String result =  alipayClient.execute(alipayRequest).getBody();

        return result;
    }
}
